<template>
  <div class="calendar-container">
    <div class="weekly-calendar">
      <div class="calendar-header">
        <div class="week-number">第{{ getNatureWeek }}周</div>
        <div class="action">
          <div class="left">
            <el-button class="btn" @click="handleToday()">返回今日</el-button>
          </div>
          <div class="center">
            <el-button class="btn" @click="handlePreWeek()">上一周</el-button>
            <div class="daterange">{{ getDateRange }}</div>
            <el-button class="btn" @click="handleNextWeek()">下一周</el-button>
          </div>
          <div class="right">
            <el-button class="btn" @click="handleCreateCourse('auto')">
              自动排课
            </el-button>
            <el-button class="btn" @click="handleCreateCourse('manual')">
              排单次课
            </el-button>
          </div>
        </div>
      </div>
      <div class="calendar-content-wrapper">
        <div class="calendar-events-container">
          <div
            v-for="(day, index) in currentWeek"
            :key="index"
            class="date-section"
            :class="{ 'is-today': day.isToday }"
          >
            <div class="week">{{ day.day }} {{ day.weekName }}</div>
            <div class="course-list">
              <div
                v-for="course in day.courseList"
                :key="course.id"
                class="course-block"
                :style="course.style"
              >
                <div class="course-wrapper">
                  <div class="action-list">
                    <div class="btn btn-edit" @click="handleEdit(course)">
                      <i class="el-icon-edit"></i>
                    </div>
                    <div class="btn btn-delete" @click="handleDelete(course)">
                      <i class="el-icon-delete"></i>
                    </div>
                  </div>
                </div>

                <div class="course-header">
                  <div class="course-title">
                    {{ course.infoClass.className }}
                  </div>
                  <div class="course-type">
                    {{ course.infoCourseType.className }}
                  </div>
                </div>
                <div class="course-body">
                  <div v-if="fieldList.includes('时间')">
                    时间：
                    {{ format(new Date(course.startDate), 'HH:mm') }}
                    {{ format(new Date(course.endDate), 'HH:mm') }}
                  </div>
                  <div v-if="fieldList.includes('老师')">
                    老师：{{ course.teacher.name }}
                  </div>
                  <div v-if="fieldList.includes('次数')">次数：</div>
                  <template v-if="fieldList.includes('学员')">
                    <div>学生名单：</div>
                    <div>
                      {{ course.students.map((d) => d.name).join(', ') }}
                    </div>
                  </template>
                </div>
              </div>

              <div
                v-for="(val, i) in timeSlotList"
                :key="i"
                class="time-slot"
                :class="{ line: val === 12 || val === 18 }"
              ></div>
            </div>
          </div>
        </div>

        <div class="time-slot-container">
          <div
            v-for="(val, index) in timeSlotList"
            :key="index"
            class="time-slot"
          >
            <div class="time">{{ val }}</div>
          </div>
        </div>
      </div>
    </div>

    <CourseEditor ref="courseEditor" @on-success="handleQueryData" />

    <IntelligentCourseCreator
      ref="intelligentCourseCreator"
      @on-success="handleQueryData"
    />
  </div>
</template>

<script>
  import {
    getDay,
    isToday,
    format,
    addDays,
    subDays,
    differenceInMinutes,
  } from 'date-fns'
  import { getCourseByPage, deleteCourse } from '@/apis/course'
  import CourseEditor from './CourseEditor'
  import IntelligentCourseCreator from './IntelligentCourseCreator'

  export default {
    name: 'CalendarWeekly',
    components: {
      CourseEditor,
      IntelligentCourseCreator,
    },
    props: {
      className: {
        type: String,
        default: null,
      },
      courseTypeId: {
        type: String,
        default: null,
      },
      fieldList: {
        type: Array,
        default: () => ['时间', '老师', '次数', '学员'],
      },
    },
    data() {
      return {
        loading: false,
        queryForm: {
          pageNum: 1,
          pageSize: 500,
          className: null,
          courseTypeId: null,
          startDate: null,
          endDate: null,
        },
        classList: [],
        // 当前日期，本周的某一天
        currentDay: new Date(),
        // 本周
        currentWeek: [],
        timeSlotList: [
          8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
        ],
        courseList: [],
      }
    },
    computed: {
      getNatureWeek() {
        const firstDay = new Date(new Date().getFullYear(), 0, 1)
        const week = firstDay.getDay()
        const finalWeek =
          (this.currentDay - firstDay + 86400000 * (week - 1)) /
          (1000 * 60 * 60 * 24 * 7)
        return parseInt(finalWeek + 1)
      },
      getDateRange() {
        const sunDay = this.currentWeek[0].date
        const saturday = this.currentWeek[6].date

        return `${format(sunDay, 'yyyy.MM.dd')} - ${format(
          saturday,
          'yyyy.MM.dd'
        )}`
      },
    },
    watch: {
      className(val) {
        this.queryForm.className = val
        this.handleQueryData()
      },
      courseTypeId(val) {
        this.queryForm.courseTypeId = val
        this.handleQueryData()
      },
      courseList: {
        handler(val) {
          if (val && val.length) {
            this.initCourseList()
          }
        },
        deep: true,
      },
    },
    created() {
      this.currentWeek = this.getWeeks(new Date())
      this.handleQueryData()
    },
    methods: {
      format,
      async handleQueryData() {
        this.loading = true

        this.queryForm.startDate = format(
          this.currentWeek[0].date,
          'yyyy-MM-dd 00:00:00'
        )
        this.queryForm.endDate = format(
          this.currentWeek[6].date,
          'yyyy-MM-dd 23:59:59'
        )

        const { list } = await getCourseByPage({
          ...this.queryForm,
        })
        this.courseList = list
        setTimeout(() => {
          this.loading = false
        }, 300)
      },
      initCourseList() {
        this.currentWeek = this.currentWeek.map((day) => {
          day.courseList = this.courseList
            .filter((d) => {
              return (
                format(day.date, 'yyyy-MM-dd') ===
                format(new Date(d.startDate), 'yyyy-MM-dd')
              )
            })
            .map((d) => {
              const { startDate, endDate } = d

              const start = new Date(startDate)
              const end = new Date(endDate)

              const height = `${(differenceInMinutes(end, start) * 160) / 60}px`
              const top = `${
                (differenceInMinutes(
                  start,
                  new Date(format(start, 'yyyy-MM-dd 08:00:00'))
                ) *
                  160) /
                60
              }px`

              d.style = {
                top,
                'min-height': height,
              }

              return d
            })

          return day
        })
      },
      // 获取本周
      getWeekName(date) {
        switch (getDay(date)) {
          case 0:
            return '周日'
          case 1:
            return '周一'
          case 2:
            return '周二'
          case 3:
            return '周三'
          case 4:
            return '周四'
          case 5:
            return '周五'
          case 6:
            return '周六'
        }
      },
      getWeeks(date) {
        const weekList = []
        const d = new Date(date)
        const day = d.getDay()

        for (let i = 0; i < 7; i++) {
          const obj = {
            date: '',
            isToday: false,
          }

          if (day == i) {
            obj.date = d
          } else if (day > i) {
            obj.date = subDays(d, day - i)
          } else {
            obj.date = addDays(d, i - day)
          }

          obj.weekName = this.getWeekName(obj.date)
          obj.day = format(obj.date, 'yyyy-MM-dd')
          obj.isToday = isToday(obj.date)

          weekList[i] = obj
        }

        return weekList
      },
      handleToday() {
        this.currentDay = new Date()
        this.currentWeek = this.getWeeks(this.currentDay)

        this.handleQueryData()
      },
      // 获取上一周
      handlePreWeek() {
        const date = subDays(this.currentDay, 7)
        this.currentDay = date
        this.currentWeek = this.getWeeks(date)

        this.handleQueryData()
      },
      //获取下一周
      handleNextWeek() {
        const date = addDays(this.currentDay, 7)
        this.currentDay = date
        this.currentWeek = this.getWeeks(date)

        this.handleQueryData()
      },
      handleCreateCourse(type) {
        if (type === 'auto') {
          this.$refs['intelligentCourseCreator'].showEdit()
        } else {
          this.$refs['courseEditor'].showEdit()
        }
      },
      handleEdit(data) {
        this.$refs['courseEditor'].showEdit(data)
      },
      handleDelete(data) {
        this.$baseConfirm('你确定要删除当前项吗', null, async () => {
          await deleteCourse([data.id])
          this.$baseMessage('操作成功', 'success')
          this.handleQueryData()
        })
      },
    },
  }
</script>

<style lang="scss" scoped>
  .calendar-container {
    overflow-x: auto;
    overflow-y: hidden;
  }

  .weekly-calendar {
    width: 100%;
    min-width: 1800px;
    padding: 16px;
    font-size: 16px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #666666;
    line-height: 22px;

    .calendar-header {
      padding: 14px;
      border-top: 1px solid #eaeaea;
      border-bottom: 1px solid #eaeaea;
      text-align: center;

      .week-number {
        text-align: center;
      }

      .action {
        display: flex;
        justify-content: space-between;

        .btn {
          font-size: 16px;
          font-family: PingFangSC-Medium, PingFang SC;
          font-weight: 500;
          color: #666666;
          background: #f8f8f8;
          border-radius: 48px;
        }

        .center {
          .daterange {
            display: inline-block;
            margin: 0 30px;
          }
        }
      }
    }

    .calendar-content-wrapper {
      position: relative;
      margin-left: 40px;

      .calendar-events-container {
        position: relative;
        display: flex;

        .date-section {
          flex: 1;

          &.is-today {
            background: #e3f2ff;
          }

          .week {
            margin: 20px 0;
            color: #74776b;
            line-height: 28px;
            text-align: center;
          }

          .day {
            font-weight: 500;
            color: #333333;
            line-height: 48px;
          }

          .course-list {
            position: relative;

            .time-slot {
              height: 160px;

              &.line {
                border: 0;
                border-top: 2px dashed #dddddd;
              }
            }
          }
        }

        .course-block {
          position: absolute;
          width: 95%;
          padding: 10px;
          background: #b9cd00;
          box-shadow: 0px 2px 10px 0px rgba(185, 205, 0, 0.3);
          border-radius: 6px;
          color: #ffffff;
          box-sizing: border-box;

          &:hover {
            .course-wrapper {
              .action-list {
                display: block;
              }
            }
          }

          .course-wrapper {
            position: relative;

            .action-list {
              position: absolute;
              top: 0;
              right: -50px;
              z-index: 10;
              display: none;

              .btn {
                width: 40px;
                height: 40px;
                border-radius: 0px 10px 10px 0px;

                i {
                  padding: 8px;
                  font-size: 22px;
                }
              }

              .btn-edit {
                background: #3ea9ff;
              }

              .btn-delete {
                margin-top: 5px;
                background: #fa6400;
              }
            }
          }

          .course-header {
            display: flex;
            justify-content: space-between;

            .course-title {
              font-weight: 600;
              line-height: 22px;
              overflow: hidden;
            }
          }

          .course-body {
            margin-top: 15px;
            font-size: 12px;
            line-height: 17px;
          }

          &.finished {
            color: #ffffff;
            background: #b9cd00;
            box-shadow: 0px 4px 20px 0px rgba(185, 205, 0, 0.3);
          }

          &.active {
            color: #ffffff;
            background: #3ea9ff;
            box-shadow: 0px 4px 10px 0px rgba(226, 240, 255, 0.5);
          }

          &.absent {
            color: #ffffff;
            background: #f8ba00;
            box-shadow: 0px 2px 10px 0px rgba(248, 186, 0, 0.3);
          }
        }
      }
    }

    .time-slot-container {
      position: absolute;
      top: 0;
      left: -40px;
      margin-top: 124px;

      .time-slot {
        .time {
          height: 160px;
          text-align: right;
          font-weight: 500;
          color: #dbdbdb;
          line-height: 28px;
        }
      }
    }
  }
</style>
